import java.util.ArrayList;
import java.util.StringTokenizer;

import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.JavaDelegate;
import org.activiti.engine.impl.el.FixedValue;
import org.activiti.engine.impl.el.Expression;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;

public class WsDelegate implements JavaDelegate{
	
	private FixedValue wsdl;
	private FixedValue operation;
	private Expression parameters;
	private FixedValue returnValue;
	
	public void execute (DelegateExecution execution) throws Exception {
				
		String wsdlString = (String)wsdl.getValue(execution);
				
		JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
		Client client = dcf.createClient(wsdlString);
				
		ArrayList<String> paramStrings = new ArrayList<String>();
				
		if (parameters != null) {
			StringTokenizer st = new StringTokenizer ((String)parameters.getValue(execution), ",");
			while (st.hasMoreTokens()) {
				String token = st.nextToken().trim();
				paramStrings.add(token);
			}
		}
		
		Object[] response = client.invoke((String)operation.getValue(execution), paramStrings.toArray(new Object[0]));
		
		System.out.println("The Web Service response is: " + response[0]);
		
		if (returnValue!=null) {
			String returnVariableName = (String) returnValue.getValue(execution);
			
			System.out.println("The Variable name is: " + returnVariableName);
			
			execution.setVariable(returnVariableName, response[0]);
		}
	}
}
